package com.app.twth.utils;

import static android.graphics.Color.BLACK;
import static android.graphics.Color.WHITE;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.pdf.PdfRenderer;
import android.os.Build;
import android.os.MemoryFile;
import android.os.ParcelFileDescriptor;
import android.util.Log;

import androidx.annotation.RequiresApi;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;

public class PDF2Bitmap {

    Context mCotext;
    ArrayList<Bitmap> mbitmaps = null;

    public PDF2Bitmap(Context con) {
        mCotext = con;
        mbitmaps = new ArrayList<Bitmap>();
    }

    /**
     * 打开PDF文件
     *
     * @param pdfPath   pdf路径
     * @param maxWeight 最大宽度
     */

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void openPDF(String pdfPath, int maxWeight, int maxHeight) {
        mbitmaps = pdfToBitmap(pdfPath, maxWeight, maxHeight);
    }

    /**
     * todo 将网络资源图片转换为Bitmap
     *
     * @param imgUrl 网络资源图片路径
     * @return Bitmap
     * 该方法调用时要放在子线程中
     */
    public Bitmap netToLoacalBitmap(String imgUrl) {
        Bitmap bitmap = null;
        InputStream in = null;
        BufferedOutputStream out = null;
        try {
            in = new BufferedInputStream(new URL(imgUrl).openStream(), 1024);
            final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
            out = new BufferedOutputStream(dataStream, 1024);
            copy(in, out);
            out.flush();
            byte[] data = dataStream.toByteArray();

            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            data = null;
            return bitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private void copy(InputStream in, OutputStream out)
            throws IOException {
        byte[] b = new byte[1024];
        int read;
        while ((read = in.read(b)) != -1) {
            out.write(b, 0, read);
        }
    }

    /**
     * PDF成功转化为Bitmap,并返回list
     */
    public ArrayList<Bitmap> getMbitmaps() {
        return mbitmaps;
    }

    /**
     * 把PDF以PNG的格式保存到本地文件夹
     *
     * @param savePath 保存路径
     */
    void savePDFToImage(String savePath) {
        if (mbitmaps == null)
            return;
        for (int i = 0; i < mbitmaps.size(); i++) {
            try {
                File file = new File(savePath);
                if (!file.exists()) {
                    file.mkdirs();
                }
                String localFile = savePath + "/" + i + ".png";
                Log.i("test_sign", "图片全路径localFile = " + localFile);
                File f = new File(localFile);
                FileOutputStream fos = new FileOutputStream(f);
                mbitmaps.get(i).compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.flush();
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private Bitmap zoomImage(Bitmap bgimage, int newWidth) {
        // 获取这个图片的宽和高
        float width = bgimage.getWidth();
        float height = bgimage.getHeight();

        // 创建操作图片用的matrix对象
        Matrix matrix = new Matrix();

        // 计算宽高缩放率
        double scale = (float) newWidth / width;

        // 缩放图片动作
        matrix.postScale((float) scale, (float) scale);

        Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
                (int) height, matrix, true);
        return bitmap;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private ArrayList<Bitmap> pdfToBitmap(String pdfPath, int maxWeight, int maxHeight) {
        File pdfFile = new File(pdfPath);
        ArrayList<Bitmap> bitmaps = new ArrayList<>();
        PdfRenderer renderer = null;
        try {
            renderer = new PdfRenderer(ParcelFileDescriptor.open(pdfFile, ParcelFileDescriptor.MODE_READ_ONLY));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (renderer == null)
            return null;
        Bitmap bitmap;
        final int pageCount = renderer.getPageCount();
        for (int i = 0; i < pageCount; i++) {
            PdfRenderer.Page page = renderer.openPage(i);
            int width = maxWeight;
            int height = maxHeight;
//            int width = page.getWidth();
//            int height = page.getHeight();

            int pageWidth = page.getWidth();
            int pageHeight = page.getHeight();
            Log.e(">>>>:", "pageWidth:" + pageWidth);
            Log.e(">>>>:", "pageHeight:" + pageHeight);
            if (pageWidth > pageHeight) {//横屏的
                width = height;//固定宽度
                height = (width * pageHeight) / pageWidth;
                if (height > maxWeight) {//宽高比例接近 , 这样打印出来多出去的部分会丢失 , 所以固定其值换算另一个
                    height = maxWeight;
                    width = (height * pageWidth) / pageHeight;
                }
            } else {
                height = (width * pageHeight) / pageWidth;
                if (height > maxHeight) {//过长,这样打印超出的部分会丢失 , 所以固定长再算宽度
                    height = maxHeight;
                    width = (height * pageWidth) / pageHeight;
                }
            }

            Log.e(">>>>:", "width:" + width);
            Log.e(">>>>:", "height:" + height);
            bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            //todo 以下三行处理图片存储到本地出现黑屏的问题，这个涉及到背景问题
            Canvas canvas = new Canvas(bitmap);
            canvas.drawColor(WHITE);
            canvas.drawBitmap(bitmap, 0, 0, null);
            Rect r = new Rect(0, 0, width, height);
            page.render(bitmap, r, null, PdfRenderer.Page.RENDER_MODE_FOR_PRINT);
//            page.render(bitmap, r, null, PdfRenderer.Page.RENDER_MODE_FOR_PRINT);

            if (bitmap.getWidth() > bitmap.getHeight()) {
                bitmap = adjustPhotoRotation(bitmap, 90);
                if (bitmap != null) {
                    Log.e(">>>>:", "bitmap.getWidth():" + bitmap.getWidth());
                    Log.e(">>>>:", "bitmap.getHeight():" + bitmap.getHeight());
                }
            }

            Log.e(">>>>:", "getWidth:" + bitmap.getWidth());
            Log.e(">>>>:", "getHeight:" + bitmap.getHeight());

            getSingleColorBitmap(bitmap);
            bitmaps.add(bitmap);
            // close the page
            page.close();
        }
        // close the renderer
        renderer.close();
        return bitmaps;
    }

    //将Bitmap转为单色位图
    private Bitmap getSingleColorBitmap(Bitmap bitmap) {
        int[] pix = new int[bitmap.getWidth() * bitmap.getHeight()];
        boolean isBitmapEmpty = true;
        for (int y = 0; y < bitmap.getHeight(); y++) {
            for (int x = 0; x < bitmap.getWidth(); x++) {
                int index = y * bitmap.getWidth() + x;
                pix[index] = WHITE;
//                if (bitmap.getPixel(x, y) != WHITE) {
//                    isBitmapEmpty = false;
//                    pix[index] = BLACK;
//                }
                if (bitmap.getPixel(x, y) < 0xFFBBBBBB) {//小于该颜色赋值黑色,防止条码出现锯齿
                    isBitmapEmpty = false;
                    pix[index] = BLACK;
                }
//                if (bitmap.getPixel(x, y) == BLACK) {
//                    isBitmapEmpty = false;
//                    pix[index] = BLACK;
//                }
            }
        }
        if (isBitmapEmpty) {
            return null;
        }
        bitmap.setPixels(pix, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
        return bitmap;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public ArrayList<Bitmap> pdfToBitmap1(String pdfPath, int maxWeight, int maxHeight) {
        File pdfFile = new File(pdfPath);
        ArrayList<Bitmap> bitmaps = new ArrayList<>();
        PdfRenderer renderer = null;
        try {
            renderer = new PdfRenderer(ParcelFileDescriptor.open(pdfFile, ParcelFileDescriptor.MODE_READ_ONLY));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (renderer == null)
            return null;
        Bitmap bitmap;
        final int pageCount = renderer.getPageCount();
        for (int i = 0; i < pageCount; i++) {
            PdfRenderer.Page page = renderer.openPage(i);
            Log.e(">>>>:", "page.getWidth():" + page.getWidth());
            Log.e(">>>>:", "page.getHeight():" + page.getHeight());
            bitmap = Bitmap.createBitmap(page.getWidth(), page.getHeight(), Bitmap.Config.ARGB_8888);
            //todo 以下三行处理图片存储到本地出现黑屏的问题，这个涉及到背景问题
            Canvas canvas = new Canvas(bitmap);
            canvas.drawColor(WHITE);
            canvas.drawBitmap(bitmap, 0, 0, null);
            page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_PRINT);

            if (bitmap.getWidth() > bitmap.getHeight()) {
                bitmap = adjustPhotoRotation(bitmap, 90);
            }
            Bitmap bitmap1 = imageCompress(bitmap, maxWeight, maxHeight);

            Log.e(">>>>:", "getWidth:" + bitmap1.getWidth());
            Log.e(">>>>:", "getHeight:" + bitmap1.getHeight());
            bitmaps.add(bitmap1);
            // close the page
            page.close();
        }
        // close the renderer
        renderer.close();
        return bitmaps;
    }

    private ParcelFileDescriptor writeToMemoryFile(byte[] bytes) {
        MemoryFile memoryFile = null;
        try {
            memoryFile = new MemoryFile("data", bytes.length);
            memoryFile.writeBytes(bytes, 0, 0, bytes.length);
            // 需要反射调用
            Method getFileDescriptorMethod = memoryFile.getClass().getDeclaredMethod("getFileDescriptor");
            if (getFileDescriptorMethod != null) {
                FileDescriptor fileDescriptor = (FileDescriptor) getFileDescriptorMethod.invoke(memoryFile);
                // 序列化，才可传送
                return ParcelFileDescriptor.dup(fileDescriptor);
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } finally {
            if (memoryFile != null) {
                memoryFile.close();
            }
        }
        return null;
    }

//    private ParcelFileDescriptor getFileDescriptor(byte[] data) {
//        ParcelFileDescriptor[] pipes = new ParcelFileDescriptor[0];
//        try {
//            pipes = ParcelFileDescriptor.createReliablePipe();
//            ParcelFileDescriptor readPipe = pipes[0];
//            ParcelFileDescriptor writePipe = pipes[1];
//            OutputStream stream = new ParcelFileDescriptor.AutoCloseOutputStream(writePipe);
//            stream.write(data);
//            stream.flush();
//            return writePipe;
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        return null;
//    }

    private ParcelFileDescriptor getFileDescriptor(byte[] fileData) {
        Log.d(">>>>", "Found " + fileData.length + " bytes of data");
        ParcelFileDescriptor[] pipe = new ParcelFileDescriptor[0];
        try {
            pipe = ParcelFileDescriptor.createPipe();
            // Stream the file data to our ParcelFileDescriptor output stream
            InputStream inputStream = new ByteArrayInputStream(fileData);
            ParcelFileDescriptor.AutoCloseOutputStream outputStream = new ParcelFileDescriptor.AutoCloseOutputStream(pipe[1]);
            int len;
            while ((len = inputStream.read()) >= 0) {
                outputStream.write(len);
            }
            inputStream.close();
            outputStream.flush();
            outputStream.close();

            // Return the ParcelFileDescriptor input stream to the calling activity in order to read
            // the file data.
            return pipe[0];
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }

    //=======================
    private Bitmap adjustPhotoRotation(Bitmap bm, final int orientationDegree) {

        Matrix m = new Matrix();
        m.setRotate(orientationDegree, (float) bm.getWidth() / 2, (float) bm.getHeight() / 2);
        float targetX, targetY;
        if (orientationDegree == 90) {
            targetX = bm.getHeight();
            targetY = 0;
        } else {
            targetX = bm.getHeight();
            targetY = bm.getWidth();
        }

        final float[] values = new float[9];
        m.getValues(values);

        float x1 = values[Matrix.MTRANS_X];
        float y1 = values[Matrix.MTRANS_Y];

        m.postTranslate(targetX - x1, targetY - y1);

        Bitmap bm1 = Bitmap.createBitmap(bm.getHeight(), bm.getWidth(), Bitmap.Config.ARGB_8888);

        Paint paint = new Paint();
        Canvas canvas = new Canvas(bm1);
        canvas.drawBitmap(bm, m, paint);


        return bm1;
    }

    public Bitmap imageCompress(Bitmap oldBitmap, int maxWeight, int maxHeight) {
        Bitmap newBitmap = oldBitmap;
        int width = oldBitmap.getWidth();//读取旧图的宽度
        int height = oldBitmap.getHeight();//读取旧图的高度
        float scaleWidth;//缩放宽度
        float scaleHeight;//缩放高度
        Matrix matrix = new Matrix();

        scaleWidth = (float) ((maxWeight * 1.0) / width);//按百分比进行缩放
        scaleHeight = (float) ((maxHeight * 1.0) / height);//同上

        matrix.postScale(scaleWidth < scaleHeight ? scaleWidth : scaleHeight, scaleWidth < scaleHeight ? scaleWidth : scaleHeight);
        newBitmap = Bitmap.createBitmap(oldBitmap, 0, 0, width, height, matrix, true);//根据缩放比例获取新图
        return newBitmap;
    }

//    private Bitmap adjustPhotoRotation(Bitmap bm, final int orientationDegree) {
//
//        String zpl = "^xa^cfa,50^fo100,100^fdHello World^fs^xz";
//        URI uri = URI.create("http://api.labelary.com/v1/printers/8dpmm/labels/4x6/0/");
//        HttpRequest request = HttpRequest.newBuilder(uri)
//                .header("Accept", "application/pdf") // omit this line to get PNG images back
//                .POST(BodyPublishers.ofString(zpl))
//                .build();
//        HttpClient client = HttpClient.newHttpClient();
//        Response response = client.send(request, BodyHandlers.ofByteArray());
//        ResponseBody body = response.body();
//
//        if (response.statusCode() == 200) {
//            File file = new File("aa.pdf"); // change file name for PNG images
//            Files.write(file.toPath(), body);
//        } else {
//            var errorMessage = new String(body, StandardCharsets.UTF_8);
//            System.out.println(errorMessage);
//        }
//    }
}
